<?php

/**
 * Created by PhpStorm.
 * User: yellow
 * Date: 2017/6/28
 * Time: 10:46
 */

namespace Admin\Controller;

use Admin\Service\CountService;

class CountController extends BaseController {


    public function __construct() {
        parent::__construct();
        $this->countService = new CountService();
    }

    public function index() {
        $cat_id = I('post.cat_id', '');
        $total = M('question')->count();
        $cat = M('categories')->where()->select();
        if($cat_id){
            $where = ' find_in_set('.$cat_id.' , cat_ids)';
            $name = M('categories')->where('id = '.$cat_id)->getField('cat_name');
            $count = M('question')
                ->where($where)->count();
            $arr[] = array('name' => $name , 'num'=>$count);
        }else{
            $select = M('question')->where()->select();
            foreach ($cat as $cid){
                $arr[$cid['id']]['name'] = $cid['cat_name'];
                foreach ($select as $val){
                    if(in_array($cid['id'] , explode(',',$val['cat_ids']))) {
                        $arr[$cid['id']]['num'] += 1;
                    }
                }
            }
        }

        $this->assign('total', $total);
        $this->assign('lists', $arr);
        $this->assign('cats', $cat);
        $this->assign('cat_id', $cat_id);
        $this->display();
    }

    public function search() {
        $this->display();
    }
    public function ajax_search() {

        $nowPage = I('get.p', 1);
        $title = I('post.title', '');
        $username = I('post.username', '');
        $mobile = I('post.mobile', '');

        $list = $this->countService->searchList($title,$username,$mobile,1);
        $page = $list['data'];

        $busConductList = $this->countService->searchList($title,$username, $mobile,0,$nowPage);

        $this->assign('page', $page->show());
        $this->assign('lists', $busConductList['data']);
        $this->display();
    }



    public function handle_count() {

        $data = I('post.');
        $res = $this->countService->handleCount($data);

        if ($res['code'] == 200 && $data['act'] != 'del') {

            $this->success('操作成功', U('Admin/count/index'));
        } elseif ($res['code'] != 200 && $data['act'] != 'del') {

            $this->error('操作失败');
        } elseif ($data['act'] == 'del') {

            $this->ajaxReturn($res);
        }
    }

}
